package com.yinlei.appserver

import java.io.ByteArrayOutputStream
import java.io.InputStream

class StreamToolkit {
    companion object{
        // 从流中读取一行，通过\r\n判断
        fun readLine(nls: InputStream): String? {
            val sb = StringBuilder()
            var c1 = 0
            var c2 = 0
            while (c2 != -1 && !(c1.toChar()=='\r' && c2.toChar() == '\n')){
                c1 = c2
                c2 = nls.read()
                sb.append(c2.toChar())
            }
            if (sb.isEmpty()){
                return ""
            }
            return sb.toString()
        }

        fun readRawFromStream(fis: InputStream) : ByteArray {
            val bos = ByteArrayOutputStream()
            val buffer = ByteArray(10240)
            var nReadaed = 0
            while(fis.read(buffer).apply {nReadaed=this} >0 ) {
                bos.write(buffer, 0 ,nReadaed)
            }
            return bos.toByteArray()
        }
    }
}